/**
 * @FileDescription: API管理
 * @Author: Liu Bowen
 * @Date:  2022-05-27
 * @LastEditTime: 2022-05-27

 * * */

import request from '@/utils/request'; // request管理
import { APILIST } from './imporApi'; // api列表

console.log(APILIST, 'APILIST');
const checkMethodType = <T extends string>(method: T, toMethodType: T): boolean => {
    return method === toMethodType || method.toLocaleUpperCase() === toMethodType;
};
let apiName: string;
const API: Service.RequestObject = {};

/** 循环APILIST追加到API中；
 * key：接口路径最后/前后两个单词命名 例如：aa/bb/cc，转为：bb_cc；
 * value： request请求体
 * */
APILIST.forEach((path: string[]) => {
    const copyPath = path;
    let [firstName, lastName] = (copyPath as unknown as string).split('/').slice(-2);

    if (path.lastIndexOf('/') + 1 === path.length) {
        const pathSlice = (path as unknown as string).substring(0, path.lastIndexOf('/'));
        [firstName, lastName] = pathSlice.split('/').slice(-2);
    }
    apiName = `${`${firstName}_${lastName}`}`;
    /**
     *  @method      请求方式
     *
     *  @data        接口参数
     *
     *  @urlVal      接口地址拼接参数（注意method形参的Val） Delete
     *
     *  @isJsonType  接口Content-Type格式
     *
     *  @loading     加载状态
     *
     */
    API[apiName] = async ({ method = 'POST', data, urlVal, isJsonType, loading = { show: false } } = {}) => {
        const requestParamData: Service.RequestParam = {
            url: checkMethodType(method, 'DELETE')
                ? `${`${path as unknown as string}/${urlVal}`}`
                : (path as unknown as string),
            method,
            loading,
            isJsonType
        };
        if (checkMethodType(method, 'GET')) {
            requestParamData.params = data;
        } else {
            requestParamData.data = data;
        }

        return await request(requestParamData);
    };
});
export default API;
